<template>
  <div>

    <div class="drainageContent">
      <div class="title rowFlex spaceBetween">
        <div class="my-el-form">
          <div class="my-el-form-label">
            开启引流
          </div>
          <div class="my-el-form-content">
            <el-switch
              v-model="ruleForm.status"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
          </div>
        </div>
        <div> <el-button
          v-if="ruleForm.media_type==2"
          @click="dialogVisible = true"
        >复用模板</el-button></div>
      </div>
      <div class="formStatus">
        <el-form
          v-show="ruleForm.status == 1"
          ref="payform"
          :model="ruleForm"
          label-width="120px"
          label-position="top"
          :rules="formRules"
        >
          <el-form-item
            label="引流类型"
            prop="media_type"
          >
            <el-radio-group v-model="ruleForm.media_type">
              <el-radio :label="1">公众号引流</el-radio>
              <el-radio :label="2">企微引流</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.media_type == 2"
            label="添加企微方式"
            prop="customer_type"
          >
            <el-radio-group
              v-model="ruleForm.customer_type"
              @change="onCustomerTypeChang"
            >
              <el-radio :label="1">添加客服号</el-radio>
              <el-radio :label="2">添加分组</el-radio>
            </el-radio-group>
          </el-form-item>
          <div
            v-if="ruleForm.media_type==1"
            class="messagesActive"
            style="margin-left:0px;width: 400px;"
          >
            <div class="icon">
              <i class="el-icon-warning"></i>
            </div>
            <div class="text">
              开启后，公众号引流配置请在小程序 - 引流规则设置
            </div>
          </div>
          <div v-else-if="ruleForm.media_type==2">
            <el-form-item
              label="添加客服"
              prop="day_fans_limit"
            >
              <div class="rowFlex allcenter">
                单个客服号/日 最多添加 <el-input
                  v-model="ruleForm.day_fans_limit"
                  :maxlength="3"
                  oninput="value=value.replace(/^0|[^0-9]/g,'')"
                  style="width:80px;margin:0 10px;"
                ></el-input> 个用户，如选中多个客服号会平均进粉
              </div>
            </el-form-item>
            <el-form-item
              label="引流方式"
              prop="scene"
            >
              <template slot="label">
                引流方式
                <el-tooltip
                  class="item"
                  effect="dark"
                  placement="top"
                >
                  <div
                    slot="content"
                    class="tooltipLine"
                  >
                    <p>如短剧启用官方播放器组件,受接口限制，"播放页-自动弹窗" 无法弹出,其他浮标引流设置不受影响</p>
                  </div>
                  <i
                    class="el-icon-question"
                    style="margin-left:2px;font-size:16px;color:#86909C;"
                  ></i>
                </el-tooltip>
              </template>
              <el-checkbox-group v-model="ruleForm.scene">
                <el-checkbox :label="1">播放页-浮标</el-checkbox>
                <el-checkbox :label="2">剧场页-浮标</el-checkbox>
                <el-checkbox :label="3">播放页-弹窗</el-checkbox>
                <el-checkbox :label="4">福利页-版位</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item>
              <div
                v-for="(item,index) in ruleForm.scene"
                :key="index"
                class="contentHandleF"
              >
                <div class="contentHandle">
                  <div class="title rowFlex spaceBetween">
                    <div class="subtitle">{{ sceneTextList.find(items => items.value === item).label }}</div>
                    <el-button @click="showAccountLayer(item)">添加客服{{ ruleForm.customer_type == 1 ? '号' : "分组" }}</el-button>
                  </div>
                  <div v-if="item===3">
                    <el-form-item
                      label="播放页弹窗设置"
                      prop="pop_strategy"
                    >
                      <el-radio-group
                        v-model="ruleForm.pop_strategy"
                        @change="onPopStrategyChange"
                      >
                        <el-radio :label="1">仅首集付费集弹</el-radio>
                        <el-radio :label="2">设置付费集弹</el-radio>
                        <el-radio :label="3">仅设置集弹</el-radio>
                        <el-radio :label="4">设置集及后每集都弹</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item
                      v-if="ruleForm.pop_strategy==2"
                      :key="numKay"
                      label="设置关注集"
                    >
                      <el-form-item prop="continuity_num">
                        <div class="set_num">连续弹出 <el-input
                          v-model="ruleForm.continuity_num"
                          style="width: 100px; margin: 0 10px;"
                          type="number"
                        ></el-input> 次</div>
                      </el-form-item>
                      <el-form-item prop="interval_num">
                        <div class="set_num">

                          每隔 <el-input
                            v-model="ruleForm.interval_num"
                            style="width: 100px; margin: 0 10px;"
                            type="number"
                          ></el-input> 集弹出一次
                        </div>
                      </el-form-item>
                    </el-form-item>
                    <el-form-item
                      v-if="ruleForm.pop_strategy==3"
                      label="设置关注集"
                      prop="num"
                    >
                      <el-select
                        v-model="ruleForm.num"
                        clearable
                        multiple
                        placeholder="请选择"
                        style="width:100%;"
                      >
                        <el-option
                          v-for="item in 50"
                          :key="item"
                          :label="'第'+item+'集'"
                          :value="item"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item
                      v-if="ruleForm.pop_strategy==4"
                      label="设置关注集"
                      prop="num"
                    >
                      <el-select
                        v-model="ruleForm.num[0]"
                        clearable
                        :multiple-limit="1"
                        placeholder="请选择"
                        style="width:100%;"
                      >
                        <el-option
                          v-for="item in 50"
                          :key="item"
                          :label="'第'+item+'集'"
                          :value="item"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </div>
                  <BiTable
                    :data="ruleForm['scene_'+(item)]"
                    size="medium"
                    :column="tableColums"
                    fixed="sticky"
                    fixed-offset="50"
                    :auto-scroll="false"
                  >
                    <template v-slot:tag_ids_name="{row}">
                      <p
                        v-for="(items,indexs) in row.tag_ids_name"
                        :key="indexs"
                      >{{ items }}</p>
                    </template>
                    <template v-slot:group_id="{row}">
                      <GroupNameVue :group-id="row.group_id"></GroupNameVue>
                    </template>
                    <template v-slot:zip="scope">
                      <el-button
                        type="text"
                        size="medium"
                        @click="sceneEdit(scope,item)"
                      >修改</el-button>
                      <el-popconfirm
                        icon="el-icon-info"
                        icon-color="red"
                        style="margin-left:10px;"
                        title="确定删除吗？"
                        @confirm="sceneDel(scope,item)"
                      >
                        <el-button
                          slot="reference"
                          type="text"
                          size="medium"
                        >删除</el-button>
                      </el-popconfirm>
                    </template>
                  </BiTable>
                </div>
              </div>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
    <span class="dialog-footer rowFlex">
      <el-button
        class="btn"
        @click="close"
      >取 消</el-button>
      <el-button
        :loading="loading"
        class="btn"
        type="primary"
        @click="onSubmit"
      >确 定</el-button>
    </span>
    <el-dialog
      title="选择"
      :visible.sync="dialogVisible"
      width="30%"
      append-to-body
      :before-close="handleClose"
    >
      <div class="copy-main">
        <div>请选择复用的小程序</div>
        <el-select
          v-model="ruleForm.mini_app_id"
          style="margin-left:10px ;"
          filterable
          remote
        >
          <el-option
            v-for="item in optionsList.mini_app"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>
      <span
        slot="footer"
        class="dialog-footer copyBtn"
      >
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          :loading="btnLoading"
          @click="onCheck"
        >确 定</el-button>
      </span>
    </el-dialog>
    <drainageAccount
      v-if="addAccount"
      :show.sync="addAccount"
      :customer-type="ruleForm.customer_type"
      :row-info="rowInfo"
      :user-info="userInfo"
      :width="700"
      title="添加客服号"
      @submit="formSubmit"
    />
  </div>
</template>

<script>
import { commonData, miniAppList } from '@/api/common'
import drainageAccount from './drainageAccount.vue'
import { drainageData, drainageSave, getCorpGroupName } from '@/api/miniApp'
import GroupNameVue from './GroupName.vue'
import { validatezero } from '@/utils/index'
export default {
  components: {
    drainageAccount,
    GroupNameVue
  },
  props: {
    rowInfo: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      btnLoading: false,
      loading: false,
      userInfo: {},
      sceneIndex: 0,
      editIndex: 0,
      handleType: 'add',
      dialogVisible: false,
      addAccount: false,
      tableData: [],
      sceneTextList: [
        {
          label: '播放页-浮标',
          value: 1
        },
        {
          label: '剧场页-浮标',
          value: 2
        },
        {
          label: '播放页-弹窗',
          value: 3
        },
        {
          label: '福利页-版位',
          value: 4
        }
      ],
      tableColums: [
        {
          label: '用户类型',
          prop: 'tag_ids_name',
          slotScope: true
        },
        {
          label: '企微主体',
          prop: 'corp_name'
        },
        {
          label: '客服号',
          prop: 'customer_name'
        },
        {
          label: '样式',
          prop: 'template_url',
          width: 80,
          render: (h, { row }) => {
            return <el-image src={row.template_url} style='width:50px;border-radius:5px;'></el-image>
          }
        },
        {
          label: '操作',
          prop: 'zip',
          width: 120,
          slotScope: true
        }
      ],
      optionsList: {
        weComBody: [],
        paycustomer_id: [],
        lookcustomer_id: [],
        tag_ids: [],
        officialList: [],
        numList: [],
        weComTemplateStyle: []
      },
      ruleForm: {
        status: 0,
        mini_app_id: '',
        customer_type: 1,
        media_type: 1,
        scene: [],
        official_app_id: '',
        official_app_name: '',
        continuity_num: '',
        interval_num: '',
        pop_strategy: 1,
        scene_1: [],
        scene_2: [],
        scene_3: [],
        scene_4: [],
        num: [],
        day_fans_limit: '',
        follow_link: 1
      },
      numKay: '',
      oldRuleForm: {
        status: 1,
        mini_app_id: '',
        customer_type: 1,
        media_type: 2,
        scene: [],
        continuity_num: '',
        interval_num: '',
        official_app_id: '',
        official_app_name: '',
        pop_strategy: 1,
        scene_1: [],
        scene_2: [],
        scene_3: [],
        scene_4: [],
        num: [],
        day_fans_limit: '',
        follow_link: 1
      },
      formRules: {
        media_type: [{ required: true, message: '请选择引流类型', trigger: 'change' }],
        scene: [{ required: true, message: '请选择引流方式', trigger: 'change' }],
        follow_link: [{ required: true, message: '请选输入关注链接', trigger: 'blur' }],
        template_id: [{ required: true, message: '请选择', trigger: 'change' }],
        official_app_id: [{ required: true, message: '请选择公众号', trigger: 'change' }],
        pop_strategy: [{ required: true, message: '请选择', trigger: 'change' }],
        num: [{ required: true, message: '请选择关注集', trigger: 'change' }],
        day_fans_limit: [{ required: true, message: '请输入', trigger: 'blur' }],
        continuity_num: [{ required: true, validator: validatezero, trigger: 'change' }],
        interval_num: [{ required: true, validator: validatezero, trigger: 'change' }]
      }
    }
  },
  watch: {
    'ruleForm.customer_type'(newVal, oldVal) {
      console.log(newVal)
      if (newVal == 1) {
        this.tableColums.splice(2, 1, {
          label: '客服号',
          prop: 'customer_name'
        })
      } else {
        this.tableColums.splice(2, 1, {
          label: '客服分组',
          prop: 'group_id',
          slotScope: true
        })
      }
    }
  },
  mounted() {
    this.onGetMiniAppList()
    this.drainageData()
  },
  methods: {
    onPopStrategyChange(value) {
      ruleForm.pop_strategy == 4 ? (ruleForm.num = []) : ''
      this.numKay = 'key' + value
    },
    onCustomerTypeChang(value) {
      const myruleForm = this.oldRuleForm
      this.oldRuleForm = { ...this.ruleForm, customer_type: value }
      this.ruleForm = { ...myruleForm, customer_type: value }
    },
    remoteMethod(query) {
      this.officialListType(query)
    },
    drainageData() {
      const data = {
        mini_app_id: this.rowInfo.id
      }
      drainageData(data).then((res) => {
        if (res.data.flow_config) {
          if (res.data.flow_config.scene_1 && res.data.flow_config.scene_1.length > 0) {
            res.data.flow_config.scene_1.map((item) => {
              if (!Array.isArray(item.customer_id)) {
                item.customer_id = [item.customer_id]
              }
            })
          }
          if (res.data.flow_config.scene_2 && res.data.flow_config.scene_2.length > 0) {
            res.data.flow_config.scene_2.map((item) => {
              if (!Array.isArray(item.customer_id)) {
                item.customer_id = [item.customer_id]
              }
            })
          }
          if (res.data.flow_config.scene_3 && res.data.flow_config.scene_3.length > 0) {
            res.data.flow_config.scene_3.map((item) => {
              if (!Array.isArray(item.customer_id)) {
                item.customer_id = [item.customer_id]
              }
            })
          }
          if (res.data.flow_config.scene_4 && res.data.flow_config.scene_4.length > 0) {
            res.data.flow_config.scene_4.map((item) => {
              if (!Array.isArray(item.customer_id)) {
                item.customer_id = [item.customer_id]
              }
            })
          }
          if (!res.data.flow_config.scene_4) {
            res.data.flow_config.scene_4 = []
          }
          const { status = 0, mini_app_id = '', customer_type = 1, media_type = 1, scene = [], official_app_id = '', official_app_name = '', continuity_num = '', interval_num = '', pop_strategy = 1, scene_1 = [], scene_2 = [], scene_3 = [], scene_4 = [], num = '', day_fans_limit = '', follow_link = 1 } = res.data.flow_config
          this.ruleForm = {
            status,
            mini_app_id,
            customer_type,
            media_type,
            scene,
            official_app_id,
            official_app_name,
            pop_strategy,
            scene_1,
            scene_2,
            scene_3,
            scene_4,
            num,
            day_fans_limit,
            follow_link,
            continuity_num,
            interval_num
          }
          if (!res.data.flow_config.customer_type) {
            this.$set(this.ruleForm, 'customer_type', 1)
          } else {
            this.ruleForm.customer_type = res.data.flow_config.customer_type * 1
          }
          console.log(this.ruleForm.customer_type)
          this.officialListType('')
        } else {
        }
      })
    },
    onSubmit() {
      if (this.ruleForm.status == 0) {
        this.confirmData()
      } else {
        this.$refs.payform.validate(async (valid) => {
          if (valid) {
            this.confirmData()
          }
        })
      }
    },
    async confirmData() {
      this.loading = true
      const data = {
        mini_app_id: this.rowInfo.id,
        flow_config: this.ruleForm
      }
      const res = await drainageSave(data)
      if (res.status_code == 1) {
        this.$message.success(res.msg)
        this.close()
      }
      this.loading = false
    },
    showAccountLayer(item) {
      console.log(item)
      this.handleType = 'add'
      this.addAccount = true
      this.sceneIndex = item
      this.userInfo = {}
    },
    officialListResult(value) {
      if (value) {
        const item = this.optionsList.officialList.find((item) => item.value === value)
        this.ruleForm.official_app_name = item.label || ''
      }
    },
    handleClose() {
      this.ruleForm.mini_app_id = ''
      this.dialogVisible = false
      this.addAccount = false
    },
    // 小程序下拉
    async onGetMiniAppList() {
      const res = await miniAppList({
        weixin_blongs_id: this.rowInfo.weixin_blongs_id
      })
      if (res.status_code === 1) {
        this.optionsList.mini_app = res.data.filter((item) => {
          return item.id != this.rowInfo.id
        })
      }
    },
    // 公众号下拉
    async officialListType(name) {
      const res = await commonData({
        type: 'officialList',
        value: name,
        page: 1,
        page_size: 20
      })
      if (this.ruleForm.official_app_name && this.ruleForm.official_app_id && name === '') {
        res.data.data.unshift({
          label: this.ruleForm.official_app_name,
          value: this.ruleForm.official_app_id
        })
        this.optionsList.officialList = res.data.data
      } else {
        this.optionsList.officialList = res.data.data
      }
    },
    formSubmit(value) {
      console.log(this.sceneIndex)
      console.log(this.ruleForm, value, this.ruleForm['scene_' + this.sceneIndex][this.editIndex])
      if (this.handleType == 'add') {
        this.ruleForm['scene_' + this.sceneIndex].push(value)
      } else {
        this.ruleForm['scene_' + this.sceneIndex].splice(this.editIndex, 1)
        this.ruleForm['scene_' + this.sceneIndex].splice(this.editIndex, 0, value)
      }
    },
    onCheck() {
      if (this.ruleForm.mini_app_id == '') {
        this.$message.warning('请选择复用的小程序')
        return
      }
      this.btnLoading = true
      const data = {
        mini_app_id: this.ruleForm.mini_app_id
      }
      drainageData(data).then(
        (res) => {
          this.btnLoading = false
          if (res.data.flow_config) {
            this.ruleForm = res.data.flow_config
          } else {
            this.$message.warning('暂无数据')
          }
          this.dialogVisible = false
        },
        (err) => {
          this.btnLoading = false
        }
      )
    },
    sceneEdit(scope, item) {
      this.handleType = 'edit'
      this.sceneIndex = item
      this.editIndex = scope.$index
      this.userInfo = scope.row
      this.addAccount = true
    },
    sceneDel(scope, item) {
      this.ruleForm['scene_' + item].splice(scope.$index, 1)
    },
    close() {
      this.$emit('cancel')
    }
  }
}
</script>

<style lang="scss" scoped>
.set_num {
  display: flex;
}
::v-deep .el-table__header-wrapper .el-table__cell {
  background: #eef0f3;
}
.rowFlex {
  z-index: 1000;
}
.drainageContent {
  padding: 20px;
  height: auto;
  padding-bottom: 100px;
}
.copy-main {
  display: flex;
  align-items: center;
}
.contentHandleF {
  background: #fff;
  margin-bottom: 20px;
}
.contentHandle {
  width: 100%;
  height: auto;
  background: #f7f8fa;
  border-radius: 3px;
  padding: 20px;
  .title {
    margin-bottom: 10px;
  }
  .subtitle {
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: bolder;
    color: #333333;
  }
}

.my-el-form {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
  .my-el-form-label {
    padding-right: 12px;
    display: flex;
    justify-content: end;
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #333333;
  }
}
::v-deep .el-form-item__label {
  font-weight: bolder;
  color: #333333;
}
.pop_strategy {
  background: #f7f8fa;
  padding: 20px;
  padding-bottom: 10px;
  border-radius: 5px;
  margin-bottom: 20px;
}
.textInfo {
  font-size: 13px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #999999;
  line-height: 25px;
  a {
    color: #3491fa;
    text-decoration: underline;
  }
}
.copyBtn {
  border: none;
}
</style>